package com.example.hello.service.impl;

import com.example.hello.service.FileStorageService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service("localFileStorageService")
public class LocalFileStorageServiceImpl implements FileStorageService {

    private static final Logger logger = LogManager.getLogger(LocalFileStorageServiceImpl.class);

    @Value("${local.storage.upload-dir:uploads}")
    private String uploadDir;
    
    @Value("${local.storage.base-url:http://localhost:8080/uploads}")
    private String baseUrl;

    @Override
    public String uploadFile(MultipartFile file, String directory) throws IOException {
        // 创建目录
        String dirPath = uploadDir + File.separator + directory;
        Path uploadPath = Paths.get(dirPath);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String extension = getFileExtension(originalFilename);
        String filename = UUID.randomUUID().toString().replace("-", "") + extension;
        
        // 保存文件
        Path filePath = uploadPath.resolve(filename);
        Files.copy(file.getInputStream(), filePath);
        
        // 返回访问URL
        String fileUrl = baseUrl + "/" + directory + "/" + filename;
        logger.info("文件上传到本地存储成功: {}", fileUrl);
        return fileUrl;
    }

    @Override
    public Map<String, String> uploadFiles(List<MultipartFile> files, String directory) throws IOException {
        Map<String, String> result = new HashMap<>();
        
        for (MultipartFile file : files) {
            String fileUrl = uploadFile(file, directory);
            result.put(file.getOriginalFilename(), fileUrl);
        }
        
        return result;
    }

    @Override
    public boolean deleteFile(String fileUrl) {
        try {
            // 从URL中提取文件路径
            String relativePath = fileUrl.replace(baseUrl + "/", "");
            Path filePath = Paths.get(uploadDir, relativePath);
            
            // 删除文件
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            logger.error("删除本地文件失败", e);
            return false;
        }
    }

    @Override
    public String generatePresignedUrl(String objectKey, int expirationMinutes) {
        // 本地存储不需要预签名URL，直接返回访问路径
        return baseUrl + "/" + objectKey;
    }
    
    private String getFileExtension(String filename) {
        if (filename == null) {
            return "";
        }
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex < 0) {
            return "";
        }
        return filename.substring(dotIndex);
    }
} 